package com.lk.utils.log;

import java.util.Map;
import java.util.Set;

import android.util.Log;

/**
 * 封装Android日志输出
 * 
 * @version 1.0.0
 * @category Utils
 * @since Sunday, May 11, 2014
 * @author kaili
 * 
 */
public class JLog {

	private boolean isDebug = true;

	private String tag = "JLog";

	private byte defaultLogType = LogType.DEBUG;

	public JLog(String tag, boolean isDebug, byte type) {
		this.isDebug = isDebug;
		this.defaultLogType = type;
		if(tag != null && !tag.equals("")){
			this.tag = tag;
		}
	}
	
	/**
	 * 打印一个Map对象，Map所装的对象须重写toString方法
	 * @param map
	 */
	public final void print(Map<String,Object> map){
		StringBuffer sb = new StringBuffer();
		if(map != null){
			for(String key : map.keySet()){
				sb.append(key);
				sb.append(" = ");
				sb.append(map.get(key).toString());
				sb.append(", ");
			}
			if(sb.length() > 0){
				sb.delete(sb.length() - 2, sb.length() - 1);
			}
		}
		print(sb.toString());
	}

	/**
	 * 将可选台数prexString与字节数组拼成字符串，并打印出来,特别注意的是这是的前缀只接收一个参数，其他多余的将不打印
	 * @param datas 字节数组
	 * @param offset 开起位
	 * @param len 长度
	 * @param prexString 前缀
	 */
	public final void print(byte[] datas, int offset, int len, String... prexString) {
		if(prexString != null && prexString.length > 0){
			print(prexString[0] + bytes2HexString(datas, offset, len));
		}else{
			print(bytes2HexString(datas, offset, len));
		}
	}

	/**
	 * 打印一个字节
	 * @param data
	 */
	public final void print(byte data) {
		String msg = Integer.toHexString(data);
		print(msg);
	}

	/**
	 * 将字节数组转化成成字符串
	 * 
	 * @param datas 要打印的字节数组
	 * @return
	 */
	private final static String bytes2HexString(byte[] datas, int offset, int len) {
		StringBuffer sb = new StringBuffer();
		String hex = "";
		for (int i = offset; i < datas.length && i < offset + len; i++) {
			hex = Integer.toHexString(datas[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex);
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * 按指定的logType输出将String通过Log输出
	 * 
	 * @param msg
	 * @param logType
	 */
	public final void print(String msg, byte logType){
		if (isDebug) {
			switch (logType) {
			case LogType.VARBOSE:
				Log.v(tag, msg);
				break;
			case LogType.INFO:
				Log.i(tag, msg);
				break;
			case LogType.WARN:
				Log.w(tag, msg);
				break;
			case LogType.ERROR:
				Log.e(tag, msg);
				break;
			case LogType.DEBUG:
				Log.d(tag, msg);
				break;

			default:
				Log.d(tag, msg);
				break;
			}
		}
	}
	
	/**
	 * 将String通过Log输出
	 * 
	 * @param msg
	 */
	public final void print(String msg) {
		print(msg, defaultLogType);
	}

	public interface LogType {
		/** 对应Log的debug */
		public final static byte DEBUG = 0x00;
		/** 对应Log的info */
		public final static byte INFO = 0x01;
		/** 对应Log的varbose */
		public final static byte VARBOSE = 0x02;
		/** 对应Log的warn */
		public final static byte WARN = 0x03;
		/** 对应Log的error */
		public final static byte ERROR = 0x04;
	}
}
